﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using DevExpress.Skins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using NNS.Enumeration;
using NNS.Framework;
using NNS.Utils.App;
using QLTB.BusinessLayer;
using QLTB.Common;
using QLTB.DieuChuyen.UI;
using QLTB.Forms;
using QLTB.Nhom.UI;
using QLTB.NSX.UI;
using QLTB.Sercurity;
using QLTB.Sercurity.UI;
using QLTB.Standard;
using QLTB.ThanhLy.UI;
using QLTB.ThietBi.UI;
using QLTB.ThongkeByLoaiTB.UI;
using QLTB.TimKiem.UI;
using QLTB.TKDieuChuyen.UI;

namespace QLTB
{
    public partial class frmMain : RibbonForm
    {
        private readonly frmFlashScreen _flashScreen = new frmFlashScreen();
        private readonly frmLogin _frmLogin = new frmLogin();
        private EnumComponent _com;
        private frmDieuChuyen _dieuChuyen;
        private frmThongKeLichSu _lichsu;
        private frmThongKeLinhKien _linhkien;
        private frmNhaCungCap _nhaCungCap;
        private frmNhom _nhom;
        private frmNSX _nsx;
        private frmThanhLy _thanhLy;
        private frmThanhLyOrder _thanhLyOrder;
        private frmThietBi _thietBi;
        private frmThongKeByLoai _thongKeByLoai;
        private frmThongKeDieuChuyen _thongKeDieuChuyen;
        private frmTimKiem _timKiem;
        private frmThongKeThietBi _tkThietBi;

        public frmMain()
        {
            //Visible = false;
            Starting += OnStarting;
            _flashScreen.Show();
            Start();
        }

        public RibbonStatusBar Status
        {
            get { return ribbonStatusBar; }
        }

        public RibbonControl MyRibbon
        {
            get { return ribbon; }
        }

        public string Message
        {
            set
            {
                lblMessage.Caption = value;
                Status.Update();
            }
        }

        public BarItemVisibility ShowProcess
        {
            set
            {
                bbiProcess.Visibility = value;
                Status.Update();
            }
        }

        public Form CurFom { get; set; }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            Update();
        }

        private event EventHandler<StartingEventArgs> Starting;

        private void OnStarting(StartingEventArgs e)
        {
            if (Starting != null) Starting(this, e);
        }


        public void SetValue(int postion)
        {
            SetValue(postion, string.Empty);
        }

        public void SetValue(int postion, string status)
        {
            if (bbiProcess.Visibility == BarItemVisibility.Never)
            {
                bbiProcess.Visibility = BarItemVisibility.Always;
                bbiProcess.Caption = "";
            }
            bbiProcess.EditValue = postion;
            bbiProcess.Caption = status;
            Status.Update();
        }

        private void Start()
        {
            OnStarting(new StartingEventArgs {ID = 0, Caption = "Nạp cấu hình...."});

            OnStarting(new StartingEventArgs {ID = 1, Caption = "Kết nối đến máy chủ...."});

            OnStarting(new StartingEventArgs {ID = 2, Caption = "Đang khởi tạo dữ liệu...."});

            OnStarting(new StartingEventArgs {ID = 3, Caption = "Đang thiết lập giao diện..."});

            OnStarting(new StartingEventArgs {ID = 4, Caption = "Đăng nhập vào hệ thống..."});

            OnStarting(new StartingEventArgs {ID = 9, Caption = "Hoàn tất"});
        }

        private void OnStarting(object sender, StartingEventArgs e)
        {
            if (_flashScreen.InvokeRequired)
            {
                EventHandler<StartingEventArgs> ob = OnStarting;
                Invoke(ob, new[] {sender, e});
            }
            else
            {
                _flashScreen.SetProcess(e.Caption, (e.ID + 1)*10);
                if (e.ID == 0)
                {
                    var frm = new frmDBOption();
                    if (!frm.Read())
                    {
                        frm.ShowDialog();
                    }
                }
                else if (e.ID == 1)
                {
                    if (!SqlHelperSmart.Check(true))
                    {
                        var frm = new frmDBOption();
                        //flashScreen.Hide();
                        MyBox.ShowWarning("Không thể kết nối đến máy chủ!\nVui lòng kiểm tra lại!", "Quản lý thiết bị");
                        frm.ShowDialog();
                    }
                }
                else if (e.ID == 2)
                {
                    InitializeComponent();
                }

                else if (e.ID == 3)
                {
                    lblDate.Caption = string.Format("{0:dd-MM-yyyy}", DateTime.Now);
                    foreach (SkinContainer skin in SkinManager.Default.Skins)
                    {
                        if (skin.SkinName.Contains("Office"))
                        {
                            BarCheckItem item = ribbon.Items.CreateCheckItem(skin.SkinName, false);
                            item.Tag = skin.SkinName;
                            item.ItemClick += OnPaintStyleClick;
                            iOffice.ItemLinks.Add(item);
                        }
                        else
                        {
                            BarCheckItem item = ribbon.Items.CreateCheckItem(skin.SkinName, false);
                            item.Tag = skin.SkinName;
                            item.ItemClick += OnPaintStyleClick;
                            iBonus.ItemLinks.Add(item);
                        }
                    }
                }
                else if (e.ID == 4)
                {
                    //InitializeComponent();
                    Enabled = false;
                    _frmLogin.Userlogined += frmLogin_Userlogined;
                    _frmLogin.Show(this);

                    _com = EnumComponent.None;
                    Show();
                }

                else if (e.ID == 9)
                {
                    _flashScreen.FadeOut();
                    _flashScreen.Hide();
                }
            }
        }

        private void frmLogin_Userlogined(object sender, EventArgs e)
        {
            if (_frmLogin.InvokeRequired)
            {
                EventHandler ob = frmLogin_Userlogined;
                Invoke(ob, new[] {sender, e});
            }
            else
            {
                Enabled = true;
                _flashScreen.SetProcess("Nạp thông tin cấu hình.. ", 50);
                //Enabled = true;
                // WindowState = FormWindowState.Normal;
                lblUser.Caption = MyLogin.Original.hoten;
                lblUnit.Caption = MyLogin.Original.iddonvi.ToString();
                var smart = new SqlHelperSmart();
                lblServer.Caption = smart.DbName;
                lblStatus.Caption = smart.Server;
                lblVersion.Caption = MyAssembly.AssemblyVersion;

                _flashScreen.SetProcess("Nạp quyền truy cập.. ", 60);
                TBL_quyenBL.IgnoreError = true;
                if (!TBL_quyenBL.isXem(EnumComponent.iUser))
                {
                    iUser.Visibility = BarItemVisibility.Never;
                }

                if (!TBL_quyenBL.isXem(EnumComponent.iPermision))
                {
                    iPermision.Visibility = BarItemVisibility.Never;
                }

                if (!TBL_quyenBL.isXem(EnumComponent.iProvider))
                {
                    iProvider.Visibility = BarItemVisibility.Never;
                }

                _flashScreen.SetProcess("Nạp quyền truy cập.. ", 70);
                if (!TBL_quyenBL.isXem(EnumComponent.iEquipment))
                {
                    iEquipment.Visibility = BarItemVisibility.Never;
                }

                if (!TBL_quyenBL.isXem(EnumComponent.iEquipmentTransfer))
                {
                    iEquipmentTransfer.Visibility = BarItemVisibility.Never;
                }

                if (!TBL_quyenBL.isXem(EnumComponent.iRequestLiquidation))
                {
                    iRequestLiquidation.Visibility = BarItemVisibility.Never;
                }

                if (!TBL_quyenBL.isXem(EnumComponent.iLiquidation))
                {
                    iLiquidation.Visibility = BarItemVisibility.Never;
                }

                if (!TBL_quyenBL.isXem(EnumComponent.iStatisticsTransfer))
                {
                    iStatisticsMove.Visibility = BarItemVisibility.Never;
                }

                if (!TBL_quyenBL.isXem(EnumComponent.iSearch))
                {
                    iSearch.Visibility = BarItemVisibility.Never;
                }
                _flashScreen.SetProcess("Nạp quyền truy cập.. ", 80);

                if (!TBL_quyenBL.isXem(EnumComponent.iBackEquipment))
                {
                    iBackEquipment.Visibility = BarItemVisibility.Never;
                }

                if (!TBL_quyenBL.isXem(EnumComponent.iStatisticsComponents))
                {
                    iStatisticsComponents.Visibility = BarItemVisibility.Never;
                }

                _flashScreen.SetProcess("Nạp quyền truy cập.. ", 90);
                if (!TBL_quyenBL.isXem(EnumComponent.iStatisticsHistoryWarranty))
                {
                    iStatisticsHistoryWarranty.Visibility = BarItemVisibility.Never;
                }
                TBL_quyenBL.IgnoreError = false;
                _flashScreen.SetProcess("Nạp quyền truy cập.. ", 100);
            }
        }


        private void timer_Tick(object sender, EventArgs e)
        {
            lblTime.Caption = string.Format("{0:hh:mm:ss}", DateTime.Now);
            lblStatus.ImageIndex = 81;
            //lblStatus.Caption = "Working Offline";
            //if (MyLib.IsAddressAvailable("vnexpress.net"))
            //{
            //    lblStatus.ImageIndex = 79;
            //    lblStatus.Caption = "Online";
            //}
        }

        private void OnPaintStyleClick(object sender, ItemClickEventArgs e)
        {
            UserLookAndFeel.Default.SkinName = e.Item.Tag.ToString();
        }

        private void iPaintStyle_ItemClick(object sender, ItemClickEventArgs e)
        {
            //dlSkin.LookAndFeel.SetSkinStyle(e.Item.Tag.ToString());
        }

        private void iOffice_Popup(object sender, EventArgs e)
        {
            foreach (BarItemLink link in iOffice.ItemLinks)
                ((BarCheckItem) link.Item).Checked = link.Item.Caption == UserLookAndFeel.Default.SkinName;
        }

        private void iBonus_Popup(object sender, EventArgs e)
        {
            foreach (BarItemLink link in iBonus.ItemLinks)
                ((BarCheckItem) link.Item).Checked = link.Item.Caption == UserLookAndFeel.Default.SkinName;
        }

        private void iProvider_ItemClick(object sender, ItemClickEventArgs e)
        {
            _com = EnumComponent.iProvider;
            Execute(_com, Actions.Show, "");
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Program._exit = true;
            _frmLogin.Style = LoginStyle.Logout;
            Destroy();
        }

        private void Destroy()
        {
            CurFom = null;
            while (MdiChildren.Length != 0)
            {
                Form form = MdiChildren[0];
                Message = "Đang đóng " + form.Text;
                form.Close();
                form.Dispose();
            }
        }

        private void iExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            Environment.Exit(0);
        }

        private void iPermisionOnItemClick(object sender, ItemClickEventArgs e)
        {
            _com = EnumComponent.iPermision;
            Execute(_com, Actions.Show, "");
        }

        private void iUserOnItemClick(object sender, ItemClickEventArgs e)
        {
            _com = EnumComponent.iPermision;
            ExecuteShow(_com, Actions.Show, "");
            ExecuteAdd(_com, Actions.Added, "");
        }


        private void ExecuteShow(EnumComponent com, Actions actions, string Ref)
        {
            if (CurFom != null)
                CurFom.Hide();
            CurFom = null;

            switch (com)
            {
                case EnumComponent.iPermision:
                    if (_nhom == null)
                    {
                        _nhom = new frmNhom {MdiParent = this};
                    }
                    if (_nhom.IsDisposed)
                    {
                        _nhom = new frmNhom {MdiParent = this};
                    }

                    CurFom = _nhom;
                    break;
                case EnumComponent.iProvider:
                    if (_nhaCungCap == null)
                    {
                        _nhaCungCap = new frmNhaCungCap {MdiParent = this};
                    }

                    if (_nhaCungCap.IsDisposed)
                    {
                        _nhaCungCap = new frmNhaCungCap {MdiParent = this};
                    }
                    CurFom = _nhaCungCap;
                    break;

                case EnumComponent.iEquipment:
                    if (_thietBi == null)
                    {
                        _thietBi = new frmThietBi {MdiParent = this};
                    }
                    if (_thietBi.IsDisposed)
                    {
                        _thietBi = new frmThietBi {MdiParent = this};
                    }
                    CurFom = _thietBi;
                    break;
                case EnumComponent.iManufacturer:
                    if (_nsx == null)
                    {
                        _nsx = new frmNSX {MdiParent = this};
                    }
                    if (_nsx.IsDisposed)
                    {
                        _nsx = new frmNSX {MdiParent = this};
                    }
                    CurFom = _nsx;
                    break;
                case EnumComponent.iBackEquipment:
                    if (_tkThietBi == null)
                    {
                        _tkThietBi = new frmThongKeThietBi {MdiParent = this};
                    }
                    if (_tkThietBi.IsDisposed)
                    {
                        _tkThietBi = new frmThongKeThietBi {MdiParent = this};
                    }
                    CurFom = _tkThietBi;
                    break;

                case EnumComponent.iSearch:
                    if (_timKiem == null)
                    {
                        _timKiem = new frmTimKiem {MdiParent = this};
                    }
                    if (_timKiem.IsDisposed)
                    {
                        _timKiem = new frmTimKiem {MdiParent = this};
                    }
                    CurFom = _timKiem;
                    break;
                case EnumComponent.iStatisticsComponents:
                    if (_linhkien == null)
                    {
                        _linhkien = new frmThongKeLinhKien {MdiParent = this};
                    }
                    if (_linhkien.IsDisposed)
                    {
                        _linhkien = new frmThongKeLinhKien {MdiParent = this};
                    }
                    CurFom = _linhkien;
                    break;
                case EnumComponent.iStatisticsHistoryWarranty:
                    if (_lichsu == null)
                    {
                        _lichsu = new frmThongKeLichSu {MdiParent = this};
                    }

                    if (_lichsu.IsDisposed)
                    {
                        _lichsu = new frmThongKeLichSu {MdiParent = this};
                    }
                    CurFom = _lichsu;
                    break;
                case EnumComponent.iStatisticsBy:
                    if (_thongKeByLoai == null)
                    {
                        _thongKeByLoai = new frmThongKeByLoai {MdiParent = this};
                    }

                    if (_thongKeByLoai.IsDisposed)
                    {
                        _thongKeByLoai = new frmThongKeByLoai {MdiParent = this};
                    }
                    CurFom = _thongKeByLoai;
                    break;

                case EnumComponent.iRequestLiquidation:
                    if (_thanhLyOrder == null)
                    {
                        _thanhLyOrder = new frmThanhLyOrder {MdiParent = this};
                    }
                    if (_thanhLyOrder.IsDisposed)
                    {
                        _thanhLyOrder = new frmThanhLyOrder {MdiParent = this};
                    }
                    CurFom = _thanhLyOrder;
                    break;

                case EnumComponent.iLiquidation:
                    if (_thanhLy == null)
                    {
                        _thanhLy = new frmThanhLy {MdiParent = this};
                    }
                    if (_thanhLy.IsDisposed)
                    {
                        _thanhLy = new frmThanhLy {MdiParent = this};
                    }
                    CurFom = _thanhLy;
                    break;

                case EnumComponent.iEquipmentTransfer:
                    if (_dieuChuyen == null)
                    {
                        _dieuChuyen = new frmDieuChuyen {MdiParent = this};
                    }
                    if (_dieuChuyen.IsDisposed)
                    {
                        _dieuChuyen = new frmDieuChuyen {MdiParent = this};
                    }
                    CurFom = _dieuChuyen;
                    break;

                case EnumComponent.iStatisticsTransfer:
                    if (_thongKeDieuChuyen == null)
                    {
                        _thongKeDieuChuyen = new frmThongKeDieuChuyen {MdiParent = this};
                    }
                    if (_thongKeDieuChuyen.IsDisposed)
                    {
                        _thongKeDieuChuyen = new frmThongKeDieuChuyen {MdiParent = this};
                    }
                    CurFom = _thongKeDieuChuyen;
                    break;
            }

            if (CurFom != null)
                CurFom.Show();
        }

        private void ExecuteAdd(EnumComponent com, Actions actions, string Ref)
        {
            switch (com)
            {
                case EnumComponent.iPermision:
                    if (_nhom.Visible)
                        _nhom.Add();
                    break;
                case EnumComponent.iEquipment:
                    if (_thietBi.Visible)
                        _thietBi.Add();
                    break;
            }
        }

        public void Execute(EnumComponent com, Actions actions, string @ref)
        {
            switch (actions)
            {
                case Actions.Show:
                    iAdd.Enabled = false;
                    Cursor cursor = Cursor.Current;
                    Cursor.Current = Cursors.WaitCursor;
                    ExecuteShow(com, actions, @ref);
                    Cursor.Current = cursor;
                    iAdd.Enabled = true;
                    break;
            }
        }

        private void iEquipment_ItemClick(object sender, ItemClickEventArgs e)
        {
            Execute(_com, Actions.Close, "");
            _com = EnumComponent.iEquipment;
            Execute(_com, Actions.Show, "");
        }


        private void iBackEquipment_ItemClick(object sender, ItemClickEventArgs e)
        {
            Execute(_com, Actions.Close, "");
            _com = EnumComponent.iBackEquipment;
            Execute(_com, Actions.Show, "");
        }


        private void iSearch_ItemClick(object sender, ItemClickEventArgs e)
        {
            Execute(_com, Actions.Close, "");
            _com = EnumComponent.iSearch;
            Execute(_com, Actions.Show, "");
        }

        private void iStatisticsComponents_ItemClick(object sender, ItemClickEventArgs e)
        {
            Execute(_com, Actions.Close, "");
            _com = EnumComponent.iStatisticsComponents;
            Execute(_com, Actions.Show, "");
        }

        private void iStatisticsHistoryWarranty_ItemClick(object sender, ItemClickEventArgs e)
        {
            Execute(_com, Actions.Close, "");
            _com = EnumComponent.iStatisticsHistoryWarranty;
            Execute(_com, Actions.Show, "");
        }


        private void iLogout_ItemClick(object sender, ItemClickEventArgs e)
        {
            //Hide();
            Destroy();
            Enabled = false;
            _frmLogin.Show(this);
            //Show();
        }


        private void iChangePassword_ItemClick(object sender, ItemClickEventArgs e)
        {
            var frm = new frmChangepassword();
            frm.ShowDialog(this);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            iExit_ItemClick(null, null);
        }


        private void frmMain_Load(object sender, EventArgs e)
        {
        }

        private void bbiUpdate_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (File.Exists(Application.StartupPath + "\\Update.exe"))
            {
                Process.Start(Application.StartupPath + "\\Update.exe");
            }
        }

        private void bbiAuthor_ItemClick(object sender, ItemClickEventArgs e)
        {
            var frmAbout = new frmAbout();
            frmAbout.ShowDialog();
        }

        private void bbiWebsite_ItemClick(object sender, ItemClickEventArgs e)
        {
            Process.Start("http://www.longanpt.com.vn");
        }

        private void iManufacturer_ItemClick(object sender, ItemClickEventArgs e)
        {
            _com = EnumComponent.iManufacturer;
            Execute(_com, Actions.Show, "");
        }

        private void iByEquipment_ItemClick(object sender, ItemClickEventArgs e)
        {
            _com = EnumComponent.iStatisticsBy;
            Execute(_com, Actions.Show, "");
        }


        private void iRequestLiquidation_ItemClick(object sender, ItemClickEventArgs e)
        {
            _com = EnumComponent.iRequestLiquidation;
            Execute(_com, Actions.Show, "");
        }

        private void iLiquidation_ItemClick(object sender, ItemClickEventArgs e)
        {
            _com = EnumComponent.iLiquidation;
            Execute(_com, Actions.Show, "");
        }

        private void iEquipmentTransfer_ItemClick(object sender, ItemClickEventArgs e)
        {
            _com = EnumComponent.iEquipmentTransfer;
            Execute(_com, Actions.Show, "");
        }

        private void iStatisticsMove_ItemClick(object sender, ItemClickEventArgs e)
        {
            _com = EnumComponent.iStatisticsTransfer;
            Execute(_com, Actions.Show, "");
        }
    }

    internal class StartingEventArgs : EventArgs
    {
        public string Caption { get; set; }

        public int ID { get; set; }
    }
}